/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package pl.edu.agh.sius.monitor;

import java.io.StringReader;

import javax.annotation.PostConstruct;
import javax.jbi.messaging.InOnly;
import javax.jbi.messaging.NormalizedMessage;
import javax.naming.InitialContext;
import javax.xml.namespace.QName;
import javax.xml.transform.stream.StreamSource;

import net.esper.client.UpdateListener;
import net.esper.event.EventBean;

import org.apache.servicemix.client.ClientFactory;
import org.apache.servicemix.client.ServiceMixClient;

public class EventListenerBean implements UpdateListener {

	@PostConstruct
	public void init(){
		try{
		ClientFactory factory =(ClientFactory) new InitialContext().lookup(ClientFactory.DEFAULT_JNDI_NAME);
		ServiceMixClient client = factory.createClient();
		
		InOnly exchange = client.createInOnlyExchange();

		NormalizedMessage message = exchange.getInMessage();
		message.setProperty("listener", this);
		String query = "select count(*) as cnt from java.lang.String.win:time(5 sec)"; 
		message.setProperty("query", query);
		message.setContent(new StreamSource(new StringReader("<hello>world</hello>")));

		// lets use a specific service to dispatch to
		QName service = new QName("http://pl.edu.agh.sius.event.provider.com", "esperProvider");
		exchange.setService(service);
		System.out.println("Trying to send: " + this.getClass().getName());
		client.send(exchange);
		System.out.println("Sended content for registration:" + this.getClass().getName());
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void update(EventBean[] newEvents, EventBean[] oldEvents) {
		if (newEvents.length > 0) {
			EventBean event = newEvents[0];
			System.out.println("count = " + event.get("cnt"));
		}
	}

}
